package com.example.demo.util.qyf;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.demo.entity.Customer;
import com.example.demo.entity.Logs;
import com.example.demo.mapper.CustomerMapper;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 支付Demo
 */
@Service
public class PayDemo {

	static String merNo = "QYF201709161363";// 商户号
	static String key = "E3E8A34F48D0B837FCDDEEDB436510D6";// 签名MD5密钥,24位
	static String reqUrl = "http://wx.qyfpay.com:90/api/pay.action";
	static String queryUrl="http://wx.qyfpay.com:90/api/queryPayResult.action";
	Logs logs = new Logs();


	@Autowired
	CustomerMapper customerMapper;

	/**
	 * 支付查询
	 *
	 * @throws UnsupportedEncodingException
	 */
	public static void payQuery() throws UnsupportedEncodingException {
		Map<String, String> metaSignMap = new TreeMap<String, String>();
		metaSignMap.put("orderNum", "20170803220058130o8i");
		metaSignMap.put("payDate", "2017-08-03");
		metaSignMap.put("merNo", merNo);
		metaSignMap.put("netway", "ZFB");// WX:微信支付,ZFB:支付宝支付
		metaSignMap.put("amount", "10000000000");// 单位:分
		metaSignMap.put("goodsName", "笔");// 商品名称：20位

		String metaSignJsonStr = ToolKit.mapToJson(metaSignMap);
		String sign = ToolKit.MD5(metaSignJsonStr + key, ToolKit.CHARSET);// 32位
		metaSignMap.put("sign", sign);

		byte[] dataStr = ToolKit.encryptByPublicKey(ToolKit.mapToJson(metaSignMap).getBytes(ToolKit.CHARSET),
				ToolKit.PAY_PUBLIC_KEY);
		String param = new BASE64Encoder().encode(dataStr);
		String reqParam = "data=" + URLEncoder.encode(param, ToolKit.CHARSET) + "&merchNo=" + metaSignMap.get("merNo")
				+ "&version=V3.0.0.0";
		String resultJsonStr = ToolKit.request(queryUrl, reqParam);
		// 检查状态
		JSONObject resultJsonObj = JSONObject.fromObject(resultJsonStr);
		String stateCode = resultJsonObj.getString("stateCode");
		if (!stateCode.equals("00")) {
			return;
		}
		String resultSign = resultJsonObj.getString("sign");
		resultJsonObj.remove("sign");
		String targetString = ToolKit.MD5(resultJsonObj.toString() + key, ToolKit.CHARSET);
		if (targetString.equals(resultSign)) {
			System.out.println("签名校验成功");
		}
	}

	/**
	 * 支付结果处理
	 * @throws Throwable
	 */
	public  void result(HttpServletRequest request, HttpServletResponse response) throws Throwable {
		String data = request.getParameter("data");
		byte[] result = ToolKit.decryptByPrivateKey(new BASE64Decoder().decodeBuffer(data), ToolKit.PRIVATE_KEY);
		String resultData = new String(result, ToolKit.CHARSET);// 解密数据
		JSONObject jsonObj = JSONObject.fromObject(resultData);
		Map<String, String> metaSignMap = new TreeMap<String, String>();
		metaSignMap.put("merNo", jsonObj.getString("merNo"));
		metaSignMap.put("netway", jsonObj.getString("netway"));
		metaSignMap.put("orderNum", jsonObj.getString("orderNum"));
		System.out.println( jsonObj.getString("orderNum").substring(20));
		metaSignMap.put("amount", jsonObj.getString("amount"));
		metaSignMap.put("goodsName", jsonObj.getString("goodsName"));
		metaSignMap.put("payResult", jsonObj.getString("payResult"));// 支付状态
		metaSignMap.put("payDate", jsonObj.getString("payDate"));// yyyyMMddHHmmss
		String jsonStr = ToolKit.mapToJson(metaSignMap);
		String sign = ToolKit.MD5(jsonStr.toString() + key, ToolKit.CHARSET);
		if (!sign.equals(jsonObj.getString("sign"))) {
			return;
		}
		logs.setIsSure(1);
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		logs.setTimeSure(sd.format(new Date()));
		logs.setLogsCode(jsonObj.getString("orderNum"));
		logs.setFalseBack("支付成功！！！！");
		customerMapper.updateLogs(logs);
		//todo 如果付款成功 则改变会员
		String b = jsonObj.getString("orderNum").substring(20);//获取用户手机号码，根据手机号码更改会员状态
		customerMapper.updateMemberState(b);
		System.out.println("签名校验成功");
		response.getOutputStream().write("0".getBytes());
	}

	/**
	 * 支付方法
	 */
	public Map<String,String> pay(String phone) throws Exception {
		Map<String,String> map = new HashMap<>();
		Map<String, String> metaSignMap = new TreeMap<String, String>();
		String orderNum = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); // 20位
		orderNum += ToolKit.randomStr(3)+phone;
		metaSignMap.put("orderNum", orderNum);
		metaSignMap.put("version", "V3.0.0.0");
		metaSignMap.put("charset", ToolKit.CHARSET);//
		metaSignMap.put("random", ToolKit.randomStr(4));// 4位随机数
		metaSignMap.put("merNo", merNo);
		metaSignMap.put("netway", "WX");// WX:微信支付,ZFB:支付宝支付
		metaSignMap.put("amount", "100");// 单位:分
		metaSignMap.put("goodsName", "认证会员");// 商品名称：20位
		metaSignMap.put("callBackUrl", "http://1833g1872k.imwork.net/customer/getppUrl");// 回调地址
		metaSignMap.put("callBackViewUrl", "http://1833g1872k.imwork.net/view");// 回显地址

		String metaSignJsonStr = ToolKit.mapToJson(metaSignMap);
		String sign = ToolKit.MD5(metaSignJsonStr + key, ToolKit.CHARSET);// 32位
//		System.out.println("sign=" + sign); // 英文字母大写
		metaSignMap.put("sign", sign);

		byte[] dataStr = ToolKit.encryptByPublicKey(ToolKit.mapToJson(metaSignMap).getBytes(ToolKit.CHARSET),
				ToolKit.PAY_PUBLIC_KEY);
		String param = new BASE64Encoder().encode(dataStr);
		String reqParam = "data=" + URLEncoder.encode(param, ToolKit.CHARSET) + "&merchNo=" + metaSignMap.get("merNo")
				+ "&version=" + metaSignMap.get("version");
		String resultJsonStr = ToolKit.request(reqUrl, reqParam);
		// 检查状态
		JSONObject resultJsonObj = JSONObject.fromObject(resultJsonStr);
		String stateCode = resultJsonObj.getString("stateCode");
		if (!stateCode.equals("00")) {
			map.put("stateCode",stateCode);
			map.put("msg",resultJsonObj.getString("msg"));
			return map;
		}
		logs.setLogsCode(orderNum);
		logs.setLogsTime( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		logs.setPhone(phone);
		logs.setLogsContent(metaSignMap.get("goodsName"));
		Double d = Double.parseDouble(metaSignMap.get("amount"));
		Integer m = d.intValue()*100;
		logs.setAmount(m);
		logs.setLogsType("2");
//		customerMapper.saveLogs(logs);
//		String resultSign = resultJsonObj.getString("sign");
		resultJsonObj.remove("sign");
//		String targetString = ToolKit.MD5(resultJsonObj.toString() + key, ToolKit.CHARSET);
//		if (targetString.equals(resultSign)) {
//			System.out.println("签名校验成功");
//		}
		map.put("stateCode",stateCode);
		map.put("code",resultJsonObj.getString("qrcodeUrl"));
		map.put("msg",resultJsonObj.getString("msg"));
		return map;
	}

}
